package com.example.util;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 字符编码过滤器
 */
public class CharacterEncodingFilter implements Filter {
    private String encoding;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        encoding = filterConfig.getInitParameter("encoding");
        if (encoding == null) {
            encoding = "UTF-8";
        }
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        HttpServletResponse httpResponse = (HttpServletResponse) response;
        
        // 确保请求和响应都使用UTF-8编码
        if (httpRequest.getCharacterEncoding() == null) {
            httpRequest.setCharacterEncoding(encoding);
        }
        
        httpResponse.setCharacterEncoding(encoding);
        
        // 添加必要的头信息确保正确编码
        if (httpResponse.getContentType() == null) {
            httpResponse.setContentType("text/html; charset=" + encoding);
        }
        
        chain.doFilter(request, response);
    }

    @Override
    public void destroy() {
        // 销毁时的清理工作
    }
} 